package cn.ibizlab.odoo.web.security.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

import lombok.extern.slf4j.Slf4j;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import cn.ibizlab.odoo.web.security.token.TokenManager;
import cn.ibizlab.odoo.util.log.IBIZLog;

@Slf4j
@IBIZLog
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    TokenManager tokenManager ;
    private String tokenHeader;

    public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,String tokenHeader) {
        super(authManager);
        this.tokenManager = tokenManager;
        this.tokenHeader = tokenHeader ;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        String headerToken = req.getHeader(tokenHeader);

        if (headerToken == null) {
            chain.doFilter(req, res);
            return;
        }
        if (headerToken.startsWith("Bearer ")) {
            String strToken = headerToken.substring(7);
            try {
                UsernamePasswordAuthenticationToken authentication = tokenManager.parseToken(strToken);
                if (authentication != null) {
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (ExpiredJwtException e) {

            }
        }
        chain.doFilter(req, res);
    }

}
